package com.qk.aspect;

import com.qk.entity.OperateLog;
import com.qk.mapper.OperateLogMapper;
import com.qk.utils.CurrentUserHoler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect//声明当前是切面类
@Component//
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;


    @Around("@annotation(com.qk.anno.Log)")//环绕通知,把自己定义的Log注解加入到对应的方法中

    public Object log(ProceedingJoinPoint pjp)throws Throwable{
    OperateLog operateLog = new OperateLog();
    operateLog.setOperateUserId(CurrentUserHoler.getCurrentUser());//获取当前用户id
    operateLog.setOperateTime(LocalDateTime.now());//获取当前时间
    operateLog.setClassName(pjp.getTarget().getClass().getName());//获取当前类名
    operateLog.setMethodName(pjp.getSignature().getName());//获取当前方法名
    operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));//获取参数

        //调用原始方法
        //记录开始时间
        long begin = System.currentTimeMillis();

        Object result = pjp.proceed();
        operateLog.setReturnValue(result.toString());
        //记录结束时间
        long end = System.currentTimeMillis();
        operateLog.setCostTime(end - begin);

        operateLogMapper.insert(operateLog);
        return result;
    }
}
